<script>
import Taro from "@tarojs/taro";
import { reactive, watch } from "vue";
import { getDicMap } from "@/utils/storage";
import { letgetDay } from "@/utils/date";
import { useQueryForm } from "./useQueryForm";
import { queryRocarsBundPageApi, deleteRocarsBundApi } from "./api";
import { useTzRouter } from "@/vhooks/useTzRouter";
import RecordList from "@/components/RecordList";
import TzVue, { useReachBottom, usePullDownRefresh } from "@/lib/TzVue";
import { useRecordListConfig } from "../hooks/useRecordListConfig";

export default new TzVue({
  name: "BundleInquireHome",
  components: { "record-list": RecordList },
  setup() {
    const { navigateTo, EventChannel, route } = useTzRouter();

    const { passControlDic, billStatusDic } = getDicMap();
    const state = reactive({
      bundleList: [],
      currentPage: 1,
      activedTabName: "7",
      queryForm: {
        type: "", // 进/出口
        docCode: "", // 六联单号
        status: "", // 单据状态
        createLoginName: "", // 录单员
        beginTime: "", // 录单时间
        endTime: "", // 录单结束时间
      },
    });

    EventChannel.on(route.path, (event) => {
      if (event?.type === "backRefresh") {
        // 刷新数据
        queryData({
          beginTime: letgetDay(-state.activedTabName),
          currentPage: 1,
          endTime: letgetDay(0),
        });
      }
    });

    usePullDownRefresh(() => {
      const { activedTabName } = state;
      if (activedTabName !== "other") {
        const params = {
          beginTime: letgetDay(-activedTabName),
          currentPage: 1,
          endTime: letgetDay(0),
        };
        queryData(params);
      }
      Taro.stopPullDownRefresh();
    });

    useReachBottom(() => {
      const { activedTabName } = state;
      if (activedTabName !== "other") {
        const params = {
          beginTime: letgetDay(-activedTabName),
          currentPage: ++state.currentPage,
          endTime: letgetDay(0),
        };
        queryData(params, true);
      }
    });

    // loading watcher
    watch(
      () => state.showLoading,
      (newVal) => {
        newVal
          ? Taro.showLoading({
              title: "加载中",
            })
          : Taro.hideLoading();
      }
    );

    // 查询捆绑数据
    const queryData = (params, isAppend) => {
      if (state.showLoading) return;
      state.showLoading = true;
      return new Promise((resolve, reject) => {
        queryRocarsBundPageApi(params)
          .then((res) => {
            state.showLoading = false;
            const { recordList, pageCount } = res.data;
            recordList.forEach((item) => {
              item.ccrns = item.ccrnList ? item.ccrnList.split(",") : [];
            });
            if (isAppend) {
              if (state.currentPage > pageCount) {
                Taro.showToast({
                  title: "已全部加载完成",
                  icon: "none",
                  duration: 2000,
                });
                // 把页数重置为上一页
                state.currentPage--;
                return;
              }
              state.bundleList.push(...recordList);
            } else {
              state.bundleList = recordList;
            }
            resolve();
          })
          .catch((err) => {
            state.showLoading = false;
            reject(err);
          });
      });
    };

    // 首次加载确报列表
    queryData({
      beginTime: letgetDay(-7),
      currentPage: 1,
      endTime: letgetDay(0),
    });

    const queryFormRender = useQueryForm(state, getDicMap, navigateTo);

    const { handleData2Cell, cellRightDataConfig } = useRecordListConfig(
      passControlDic,
      billStatusDic
    );

    const handleBtnClick = (data) => {
      const { id } = data.data;
      if (data.hanldeName === "delete") {
        Taro.showModal({
          content: "确定删除该条记录吗?",
          confirmText: "确定",
          cancelText: "取消",
        }).then((res) => {
          res.confirm &&
            deleteRocarsBundApi(id).then(() => {
              const params = {
                beginTime: letgetDay(-state.activedTabName),
                currentPage: 1,
                endTime: letgetDay(0),
              };
              queryData(params);
            });
        });
      } else if (["receipt", "receiptAndShot"].includes(data.hanldeName)) {
        navigateTo({
          path: "/pages/subHK/bundleInquire/receipt/index",
          query: {
            docId: id,
          },
        });
      }
    };

    const listItemClick = (data) => {
      navigateTo({
        path: "/pages/subHK/bundleInquire/details/index",
        query: {
          bundId: data.id,
        },
      });
    };

    const recordListRender = () => {
      return (
        <record-list
          dataList={state.bundleList}
          cellList={handleData2Cell}
          onBtnClick={handleBtnClick}
          onItemClick={listItemClick}
          cellRightDataConfig={cellRightDataConfig}
        ></record-list>
      );
    };

    const handleTabClick = (tabName) => {
      if (tabName !== "other") {
        state.currentPage = 1;
        const params = {
          beginTime: letgetDay(-tabName),
          currentPage: 1,
          endTime: letgetDay(0),
        };
        queryData(params);
      }
    };

    return () => {
      return (
        <tz-view class="bundle-inquire-home">
          <tz-tabs v-model={state.activedTabName} onTabClick={handleTabClick}>
            <tz-tab-pane label="七天内" name="7">
              {recordListRender()}
            </tz-tab-pane>
            <tz-tab-pane label="一个月内" name="30">
              {recordListRender()}
            </tz-tab-pane>
            <tz-tab-pane label="条件查询" name="other">
              {queryFormRender()}
            </tz-tab-pane>
          </tz-tabs>
        </tz-view>
      );
    };
  },
});
</script>

<style lang="scss">
.bundle-inquire-home {
  .query-block {
    display: flex;
    flex-direction: column;
    .query-form {
      background-color: $white;
      padding: 0 15px;
      .tz-cell {
        &:last-child:after {
          border: none;
        }
        picker {
          .placeholder {
            color: $placeholder-color;
          }
        }
        .tz-icon-scan {
          color: $info-color-active;
        }
      }
    }
    .search-btn {
      align-self: center;
      width: 345px;
      margin-top: 20px;
      height: 44px;
    }
  }
  .record-list .data-list-item .info-area .tz-cell-label {
    width: 100px;
  }
}
</style>
